<template>
  <div class="box">
    <!-- 头部导航 -->
    <van-nav-bar
      class="nav"
      title="欢迎注册"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <!-- 标题 -->
    <h2>优点达资讯</h2>
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        left-icon="manager"
        name="mobile"
        label="用户名"
        placeholder="手机号"
        :rules="rules.username"
      />
      <van-field
        v-model="password"
        left-icon="lock"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="rules.password"
      />
      <van-field
        v-model="epassword"
        left-icon="lock"
        type="password"
        name="epassword"
        label="确认密码"
        placeholder="确认密码"
        :rules="[{ validator, message: '密码不一致' }]"
      />
      <div style="margin: 16px">
        <van-button class="button" round block type="info" native-type="submit"
          >注册</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { registerAPI } from '@/api/login'
import { Toast } from 'vant'
export default {
  data () {
    return {
      username: '',
      password: '',
      epassword: '',

      // 验证规则
      rules: {
        // 手机号验证规则
        username: [
          { required: true, message: '请输入手机号' },
          { pattern: /1[0-9]{10}/, message: '手机格式错误' }
        ],
        // 密码验证规则
        password: [
          { required: true, message: '请填写密码' },
          {
            pattern: /^[a-zA-Z]([0-9]|[a-zA-Z]){5}/,
            message: '密码格式：字母开头，6-12位'
          }
        ]
      }
    }
  },
  methods: {
    onClickLeft () {
      console.log('返回')
    },
    async onSubmit (val) {
      const { data: res } = await registerAPI(val)
      console.log(res)
      // 数据判断
      if (res.errmsg === '注册成功') {
        // 提示信息
        Toast.success('注册成功')
        // 页面跳转到登录
        this.$router.push('/login')
      } else {
        Toast.fail(res.errmsg)
      }
    },
    // 重复密码验证规则
    validator () {
      return this.password === this.epassword
    }
  }
}
</script>

<style scoped lang="less">
.box {
  // 导航
  .nav {
    background-color: #003366;
    ::v-deep .van-nav-bar__title {
      color: #fff;
    }
  }
  // 底部去注册按钮
  .van-nav-bar {
    ::v-deep .van-nav-bar__text {
      color: #003366;
    }
  }

  // 返回按钮
  ::v-deep .van-nav-bar .van-icon {
    color: #fff;
  }
  .button {
    background-color: #003366;
    border: none;
  }

  h2 {
    font-weight: 400;
    text-align: center;
    color: #003366;
  }
  ::v-deep .van-hairline--bottom::after {
    border-bottom: 0;
  }
}
</style>
